<template>
  <div id="app">
    <el-card class="login-card">
      <!-- 绑定数据 -->
      <el-form ref="form" :model="formData" :rules="rules">
        <h2>用户登录</h2>
        <el-form-item prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="formData.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="formData.password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="submit-btn" type="primary" @click="handLogin">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      formData: {
        username: "",
        password: "",
      },
      // 制定规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            // 利用正则来校验
            pattern: /^1[3-9][0-9]{9}$/,
            message: "用户名不符合规范",
            trigger: "change",
          },
          {
            // 自定义校验规则
            validator: function (rule, value, callback) {
              if (value[2] === '0') {
                callback();
              } else {
                callback(new Error("第三位必须是0"));
              }
            },
          },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods : {
    async handLogin() {
      // 手动校验
      // 回调函数
      // this.$refs.form.validate(function(isOk) {
      //   if(isOk) {
      //     console.log('通过');
      //   } else {
      //     console.log('未通过');
      //   }
      // })

      // Promise方式
      // this.$refs.form.validate()
      // .then(() => {
      //   console.log('通过');
      // })
      // .catch(() => {
      //   console.log('未通过');
      // })

      // 异步转同步
      try {
        await this.$refs.form.validate()
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>

<style>
* {
  padding: 0;
  margin: 0;
}

#app {
  width: 100%;
  height: 100vh;
  background-color: #eee;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-card {
  width: 400px;
}

.login-card h2 {
  font-weight: normal;
  text-align: center;
  margin-bottom: 30px;
}

.login-card .submit-btn {
  width: 100%;
}
</style>
